package com.kotlin.book.adapter

import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.databinding.ItemReadTextBinding
import com.kotlin.book.entry.Chapter

class ReadTextItemAdapter(private var itemList: List<Chapter>, private val callback:(Int)->Unit) :
    RecyclerView.Adapter<ReadTextItemAdapter.ItemViewHolder>() {

    class ItemViewHolder(itemBinding: ItemReadTextBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {

        val title: TextView = itemBinding.title
        val text: TextView = itemBinding.text
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val binding =
            ItemReadTextBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = itemList[position]
        holder.title.text = item.name
        holder.text.text = item.content

        holder.itemView.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    callback(holder.adapterPosition)
                }
            }
            false
        }
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    fun setData(newChapters: List<Chapter>) {
        itemList = newChapters
    }
}
